import { Injectable, OnApplicationBootstrap } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { DetailPage } from '@/modules/detail-page/entities/detail-page.entity'
import {
  CreateDetailPageDto,
  FindOneDetailPageDto,
  UpdateDetailPageDto,
} from './dto/detail-page.dto'

@Injectable()
export class DetailPageService implements OnApplicationBootstrap {
  constructor(
    @InjectRepository(DetailPage)
    private downloadRepository: Repository<DetailPage>,
  ) {}

  async onApplicationBootstrap() {
    const exists = await this.findOne({})
    if (!exists) {
      await this.create({})
      console.log('详情页配置已初始化')
    }
  }

  create(data: CreateDetailPageDto) {
    return this.downloadRepository.save(data)
  }

  async findOne(data: FindOneDetailPageDto) {
    return await this.downloadRepository.findOneBy(data)
  }

  async update(detailPageId: number, data: UpdateDetailPageDto) {
    return this.downloadRepository.update(detailPageId, {
      ...data,
      detailPageId: undefined,
    })
  }

  remove(detailPageId: number) {
    return this.downloadRepository.delete(detailPageId)
  }
}
